//
//  AuthViewController.swift
//  WEIBO
//
//  Created by 谢曦 on 2017/5/6.
//  Copyright © 2017年 谢曦. All rights reserved.
//

import UIKit
import SVProgressHUD
class AuthViewController: UIViewController {

    private lazy var  webView = UIWebView()
    private  var  user = AccountModel()
    //重写
    override func loadView() {
       view=webView
        view.backgroundColor=UIColor.white
        webView.delegate=self
        navigationItem.rightBarButtonItem=UIBarButtonItem.init(themeBtnTitle: "返回", target: self, action: #selector(back))
        setWebVeiw()
        
    }
    

    
     // MARK: - override
    

    override func viewDidLoad() {
        super.viewDidLoad()

    }

        // MARK: -
    
    private func setWebVeiw(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        let url = URL.init(string:urlString )
        guard let d_url=url else {
            return
        }
        
        let request = URLRequest.init(url: d_url)
        
       webView.loadRequest(request)
    
    
    }
 // MARK: - action
   @objc private func back()  {
        
    }
  private  func close() {
        
    }

    
    fileprivate   func requstAccessToken(code:String,completion:@escaping (_ isSuccess:Bool) -> ()) -> (){
        let urlString = "https://api.weibo.com/oauth2/access_token"
    
        let params = ["client_id": appKey,
                      "client_secret": appSecrect,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": redirectUrl]
        
//   NetworkManager.shareInstance.request(type: .POST, url: urlString, param: params as [String:AnyObject], suc
    
        NetworkManager.shareInstance.request(type: .POST, url: urlString, param: params as [String:AnyObject], success: { (response) in
            //   保存
            self.user.saveUser(userDict:response)
            completion(true)
          //通知首页刷新界面
            
            let note =  Notification.init(name: Notification.Name("loginSuccessNotification"))
            NotificationCenter.default.post(note)
            
         }, failure: { (error) in
             completion(false)
        
            print(error)
  
        })
    }


    
    
    
    
 
}

extension AuthViewController:UIWebViewDelegate{

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.absoluteString.hasPrefix(redirectUrl)==false {
            //启动授权界面
            return true
        }
        else
        {
            //授权成功调用
//         request.url   http://www.baidu.com/?code=2e66e5013e206920590b9f7bb15e50ea
            let codeStr = request.url?.query
            let code = codeStr?.substring(from: "code=".endIndex) ?? ""
          
           //使用授权码获取[换取] AccessToken
            requstAccessToken(code: code, completion:{
            (isSuccess) in
                if isSuccess == true{
                self.dismiss(animated: true, completion: { 
                    
                })
                }
                
                else{
                SVProgressHUD.showError(withStatus: "登录失败，服务器异常")
                }
            
            } )
            return false
        }
     
        
    }
}
